'use client';

import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message, Divider } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuth } from '@/contexts/AuthContext';
import styles from './Login.module.scss';

interface LoginForm {
  emailOrUsername: string;
  password: string;
}

interface RegisterForm {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
  displayName?: string;
}

export default function AuthPage() {
  const [isLogin, setIsLogin] = useState(true);
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const { login } = useAuth();
  const [loginForm] = Form.useForm<LoginForm>();
  const [registerForm] = Form.useForm<RegisterForm>();
  const [licenseError, setLicenseError] = useState<string | null>(null);
  const [licenseValid, setLicenseValid] = useState<boolean>(true);

  useEffect(() => {
    fetch('/api/license/status').then(async (res) => {
      const result = await res.json();
      if (result.status !== 200) {
        setLicenseError(result.message || '未授权，禁止登录');
        setLicenseValid(false);
      } else {
        setLicenseValid(true);
      }
    }).catch(() => {
      setLicenseError('无法获取授权状态');
      setLicenseValid(false);
    });
  }, []);

  // 登录处理
  const handleLogin = async (values: LoginForm) => {
    setLoading(true);
    try {
      const success = await login(values.emailOrUsername, values.password);
      if (success) {
        // 登录成功后跳转到首页或之前的页面
        const returnUrl = new URLSearchParams(window.location.search).get('returnUrl') || '/';
        router.push(returnUrl);
      }
    } catch (error) {
      console.error('登录错误:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 注册处理
  const handleRegister = async (values: RegisterForm) => {
    if (values.password !== values.confirmPassword) {
      message.error('两次输入的密码不一致');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: values.username,
          email: values.email,
          password: values.password,
          displayName: values.displayName,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        message.success(data.message || '注册成功');
        // 注册成功后跳转到首页
        router.push('/');
      } else {
        message.error(data.error || '注册失败');
      }
    } catch (error) {
      console.error('注册错误:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.loginContainer}>
      <Card className={styles.loginCard}>
        {/* 标题区域 */}
        <div className={styles.header}>
          <div className={styles.logo}>
            AI
          </div>
          <h1 className={styles.title}>
            AIGC教育平台
          </h1>
          <p className={styles.subtitle}>
            {isLogin ? '登录您的账户' : '创建新账户'}
          </p>
        </div>

        {licenseError && <div style={{ color: '#cf1322', marginBottom: 16, textAlign: 'left' }}>{licenseError}</div>}

        {/* 切换标签 */}
        <div className={styles.tabContainer}>
          <button
            className={`${styles.tabButton} ${isLogin ? styles.active : ''}`}
            onClick={() => setIsLogin(true)}
          >
            登录
          </button>
          <button
            className={`${styles.tabButton} ${!isLogin ? styles.active : ''}`}
            onClick={() => setIsLogin(false)}
          >
            注册
          </button>
        </div>

        {/* 表单区域 */}
        <div className={styles.formContainer}>
          {isLogin ? (
            <Form
              form={loginForm}
              name="login"
              onFinish={handleLogin}
              layout="vertical"
              size="large"
            >
              <Form.Item
                name="emailOrUsername"
                label="邮箱/用户名"
                rules={[
                  { required: true, message: '请输入邮箱或用户名' },
                ]}
                className={styles.formItem}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="请输入邮箱或用户名"
                  disabled={!licenseValid}
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: '请输入密码' }]}
                className={styles.formItem}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请输入密码"
                  disabled={!licenseValid}
                />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  className={styles.submitButton}
                  disabled={!licenseValid}
                >
                  登录
                </Button>
              </Form.Item>
            </Form>
          ) : (
            /* 注册表单 */
            <Form
              form={registerForm}
              name="register"
              onFinish={handleRegister}
              layout="vertical"
              size="large"
            >
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, message: '用户名至少3个字符' },
                ]}
                className={styles.formItem}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="请输入用户名"
                  disabled={!licenseValid}
                />
              </Form.Item>

              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
                className={styles.formItem}
              >
                <Input
                  prefix={<MailOutlined />}
                  placeholder="请输入邮箱"
                  disabled={!licenseValid}
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6个字符' },
                ]}
                className={styles.formItem}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请输入密码"
                  disabled={!licenseValid}
                />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                label="确认密码"
                dependencies={['password']}
                rules={[
                  { required: true, message: '请确认密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
                className={styles.formItem}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请再次输入密码"
                  disabled={!licenseValid}
                />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  className={styles.submitButton}
                  disabled={!licenseValid}
                >
                  注册
                </Button>
              </Form.Item>
            </Form>
          )}
        </div>

        {/* 底部区域 */}
        <div className={styles.footer}>
          <Divider className={styles.divider}>
            <span>其他方式</span>
          </Divider>

          <div className={styles.links}>
            <Link href="/docs" className={styles.link}>
              查看API文档
            </Link>
            <span className={styles.copyright}>
              © 2024 AIGC教育平台
            </span>
          </div>
        </div>
      </Card>
    </div>
  );
}